package io;

import java.io.FileNotFoundException;
import java.io.IOException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.List;
import java.util.Properties;

import data.Document;

public class DBDatasetWriter
{

	private String m_DbUser;
	private String m_DbPwd;
	private String m_DbName;
	private String m_DbIp;
	private String m_Port;
	private String m_SourceTable;
	private String m_DbUrl;
	
	public DBDatasetWriter()
	{
		String driverClass = "com.microsoft.sqlserver.jdbc.SQLServerDriver";
		Properties prop = null;
		try
		{
			Class.forName(driverClass);
		
			final String propFile = "data\\conf.properties";
			PropertiesLoader propLoader = new PropertiesLoader(propFile);
			prop = propLoader.getPropertiesObject();
		
		} catch (ClassNotFoundException e)
		{
			e.printStackTrace();
		} catch (FileNotFoundException e)
		{
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e)
		{
			// TODO Auto-generated catch block
			e.printStackTrace();
		} 
		
		if(null == prop)
		{
			prop = new Properties();
			prop.setProperty("dbName", "KNNTest");
			prop.setProperty("dbIP", "192.168.0.6");
			prop.setProperty("dbPort", "1433");
			prop.setProperty("trainingData", "docs");
			prop.setProperty("sourceData", "testClassify");
			prop.setProperty("dbUser", "sa");
			prop.setProperty("dbPwd", "mobey");
			prop.setProperty("tokenDelimiter", "\t");
			prop.setProperty("valueDelimiter", ",");
		}
		
		m_DbName = prop.getProperty("dbName");
		m_DbIp = prop.getProperty("dbIP");
		m_Port = prop.getProperty("dbPort");
		m_SourceTable = prop.getProperty("sourceData");
		m_DbUser = prop.getProperty("dbUser");
		m_DbPwd = prop.getProperty("dbPwd");
		
		m_DbUrl = "jdbc:sqlserver://" + m_DbIp + ":" + m_Port + ";DatabaseName=" + m_DbName;
		
	}
	
	public void writeToDB(List<Document<String, Integer>> docs)
	{
		Connection con = null;
		Statement stmt = null;
		
		try
		{
			con = DriverManager.getConnection(m_DbUrl,m_DbUser,m_DbPwd);
			stmt = con.createStatement();
			for(Document<String, Integer> doc : docs)
			{
				String updateData = "update " + m_SourceTable +" set minerClass=" 
					+ doc.getClassId() + ", majorClass=" + doc.getMajorId() + " where id=" + doc.getId();
				stmt.execute(updateData);
			}
			
			stmt.close();
			con.close();
			
		} catch (SQLException e)
		{
			e.printStackTrace();
		}
	}
	
}
